package com.cdtye.itps.cms.service.rowdata;


import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cdtye.common.authcore.model.UserSso;
import com.cdtye.common.authcore.util.AuthHelper;
import com.cdtye.common.mybatiscore.base.BaseService;
import com.cdtye.common.webcore.constants.WebConstants;
import com.cdtye.common.webcore.util.DateUtil;
import com.cdtye.common.webcore.web.BizException;
import com.cdtye.itps.cms.dao.categoryreport.entity.JcjcCategoryReport;
import com.cdtye.itps.cms.dao.categoryreport.entity.JcjcCatrgoryImportExcel;
import com.cdtye.itps.cms.dao.cid.entity.JcjcUnitCidData;
import com.cdtye.itps.cms.dao.deduction.entity.JcjcKmDeduction;
import com.cdtye.itps.cms.dao.deduction.entity.JcjcKmDeductionExcel;
import com.cdtye.itps.cms.dao.defect.entity.JcwProblemDefectCategory;
import com.cdtye.itps.cms.dao.defect.entity.JcwProblemDefectLevel;
import com.cdtye.itps.cms.dao.dept.entity.SysDept;
import com.cdtye.itps.cms.dao.direction.entity.JcDirection;
import com.cdtye.itps.cms.dao.rowdata.entity.JcjcRowDataImportLog;
import com.cdtye.itps.cms.dao.rowdata.entity.JcjcUnitCidDataExcel;
import com.cdtye.itps.cms.dao.rowdata.vo.JcjcRowDataImportLogExcalVo;
import com.cdtye.itps.cms.dao.rowdata.vo.JcjcRowDataImportLogVo;
import com.cdtye.itps.cms.dao.summary.entity.JcjcEvalauationSummary;
import com.cdtye.itps.cms.mapper.rowdata.JcjcRowDataImportLogMapper;
import com.cdtye.itps.cms.service.categoryreport.JcjcCategoryReportService;
import com.cdtye.itps.cms.service.cid.JcjcUnitCidDataService;
import com.cdtye.itps.cms.service.deduction.JcjcKmDeductionService;
import com.cdtye.itps.cms.service.defect.JcwProblemDefectCategoryService;
import com.cdtye.itps.cms.service.defect.JcwProblemDefectLevelService;
import com.cdtye.itps.cms.service.dept.SysDeptService;
import com.cdtye.itps.cms.service.direction.JcDirectionService;
import com.cdtye.itps.cms.service.summary.JcjcEvalauationSummaryService;
import com.cdtye.itps.cms.util.DateUtils;
import com.cdtye.itps.cms.util.ExpCommonHelper;
import com.cdtye.itps.models.base.model.attr.basic.LineAttr;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 原始数据导入记录表 服务类
 * @author Jchen
 * @date 2021-09-24
 */
@Service
public class JcjcRowDataImportLogService extends BaseService<JcjcRowDataImportLogMapper, JcjcRowDataImportLog> {
    @Autowired
    private JcjcRowDataImportLogMapper modelMapper;

    @Autowired
    private SysDeptService sysDeptServices;

    @Autowired
    private JcjcEvalauationSummaryService jcjcEvalauationSummaryServices;

    @Autowired
    private JcwProblemDefectLevelService jcwProblemDefectLevelServices;

    @Autowired
    private JcwProblemDefectCategoryService jcwProblemDefectCategoryServices;

    @Autowired
    private JcjcCategoryReportService jcjcCategoryReportServices;

    @Autowired
    private JcjcKmDeductionService jcjcKmDeductionServices;

    @Autowired
    private JcjcUnitCidDataService jcjcUnitCidDataServices;


    @Autowired
    private JcDirectionService jcDirectionServices;



    /**
     * 列表查询
     */
    public List<JcjcRowDataImportLog> list(JcjcRowDataImportLogVo vo){
        LambdaQueryWrapper<JcjcRowDataImportLog> wrapper = new LambdaQueryWrapper<>();
        //添加查询条件

        //物理删除表,查询非删除状态包括null
        wrapper.and(i->i.eq(JcjcRowDataImportLog::getDelFlag, WebConstants.NO).or().isNull(JcjcRowDataImportLog::getDelFlag));
        return modelMapper.selectList(wrapper);
    }

    /**
     * 分页查询，自定义sql语句
     * @param vo
     * @return
     */
    public List<JcjcRowDataImportLog> listPage(JcjcRowDataImportLogVo vo){
        QueryWrapper<JcjcRowDataImportLog> objectQueryWrapper = new QueryWrapper<>();
        objectQueryWrapper.orderByDesc("CREATE_DATETIME");
        List<JcjcRowDataImportLog> jcjcRowDataImportLogs = modelMapper.selectList(objectQueryWrapper);
        for (JcjcRowDataImportLog j:jcjcRowDataImportLogs) {
            if(j.getStatus().equals("0")){
                j.setStatus("导入成功");
            }else {
                j.setStatus("导入失败");
            }
        }
        return jcjcRowDataImportLogs;
    }


    /**
     * 文件导入 --table1:缺陷报表（JcjcCatrgoryReport）  table2：每公里分数统计(JcjcKmDeduction)  table3：单元CDI数据(JcjcUnitCidData)
     */

    public Object importFile(MultipartFile file){
        String originalFilename = file.getOriginalFilename();
        Workbook workbook;
        InputStream inputStream;
        Sheet sheet;
        //读取文件,判断文件名
        try {
            inputStream = file.getInputStream();
            if(originalFilename.endsWith(".xls")){
                workbook = new HSSFWorkbook(inputStream);
            }else {
                workbook = new XSSFWorkbook(inputStream);
            }
            sheet = workbook.getSheetAt(2);

            if (!workbook.getSheetAt(2).getSheetName().equals("缺陷报表")||!workbook.getSheetAt(3).getSheetName().equals("每公里扣分数统计")||!workbook.getSheetAt(4).getSheetName().equals("单元CDI数据")){
                throw new BizException("读取Excel失败 sheet名称不符");
            }
        } catch (Exception e) {
            throw new BizException("读取Excel失败");
        }
        //读取Excel标题
        try {
            Row row = sheet.getRow(0);
            if (row == null) {
                row = sheet.createRow(0);
            }
            Cell cell = row.getCell(0);
            String cellValue = cell.getStringCellValue();

        }catch (Exception e){
            throw new BizException("读取Excel 标题失败");
        }

//        QueryWrapper<JcjcRowDataImportLog> wrapper = new QueryWrapper<>();
//        wrapper.eq("FILE_NAME",file.getOriginalFilename());
//        if(!modelMapper.selectList(wrapper).isEmpty()){
//            throw new BizException(file.getOriginalFilename()+"已导入，不可重复导入");
//        }
        //保存导入记录
        JcjcRowDataImportLogExcalVo vo = new JcjcRowDataImportLogExcalVo();
        //导入日志信息存入
        JcjcRowDataImportLog jcjcRowDataImportLog = new JcjcRowDataImportLog();
        //获取文件名字
        jcjcRowDataImportLog.setFileName(file.getOriginalFilename());
        //文件状态
        jcjcRowDataImportLog.setStatus("0"); //默认成功
        UserSso loginUser = AuthHelper.loginUser();
        Date nowDate = DateUtil.getDateTime();
        jcjcRowDataImportLog.setCreateBy(loginUser.getId());
        jcjcRowDataImportLog.setCreateDatetime(nowDate);
        jcjcRowDataImportLog.setDelFlag("N");
        jcjcRowDataImportLog.setRemark("正在上传请稍后······");
        modelMapper.insert(jcjcRowDataImportLog);

        ImportParams params = new ImportParams();
        //单元CDI数据列表
        List<JcjcUnitCidDataExcel> cdiList;
        //缺陷报表列表
        List<JcjcCatrgoryImportExcel> cateList;
        //每公里扣分数统计列表
        List<JcjcKmDeductionExcel> kmList;
        Map<String,String> errMsg = new HashMap<>();
        Map<String,Integer> successCdi = new HashMap<>();
        Map<String,Integer> successCate = new HashMap<>();
        Map<String,Integer> successKm = new HashMap<>();
        params.setTitleRows(0);
        params.setStartSheetIndex(2);
        try {
            cateList = ExcelImportUtil.importExcel(file.getInputStream(), JcjcCatrgoryImportExcel.class, params);
        } catch (Exception e) {
            throw new BizException("读取Excel失败");
        }

        params.setTitleRows(0);
        params.setStartSheetIndex(3);
        try {
            kmList = ExcelImportUtil.importExcel(file.getInputStream(), JcjcKmDeductionExcel.class, params);
        } catch (Exception e) {
            throw new BizException("读取Excel失败");
        }

        params.setTitleRows(0);
        params.setStartSheetIndex(4);
        try {
            cdiList = ExcelImportUtil.importExcel(file.getInputStream(), JcjcUnitCidDataExcel.class, params);
        } catch (Exception e) {
            throw new BizException("读取Excel失败");
        }


        Map<String,String > deptMap = deptMap();
        Map<String,String> deptUnitMap = deptUnitMap();
        Map<String,String> defectCategoryMap = defectCategoryMap();
        Map<String,String> defectLevelMap = defectLevelMap();
        Map<String,String> directionMap = directionMap();

        //已获取到数据  现在解析第一个table  缺陷报表  JCJC_CATEGORY_REPORT
        Map<String,String> levelMap = new HashMap<>();
        //缺陷等级名称转换
        levelMap.put("1","一级类");
        levelMap.put("2","二级A类");

        //查询出所有的线路和所属部门，验证数据
        List<Map<String,String>> list = modelMapper.getSecline();
        List<Map<String,Object>> unitList = modelMapper.getSecLineUnitManage();
        Map<String,Map<String,String>> lineMaps = new HashMap<>();
        for (Map<String,String> m: list) {
            lineMaps.put(m.get("seclineName"),m);
        }

        Map<String,String> lineRuleMap = new HashMap<>();
        List<JcjcCategoryReport> jcjcCategoryReports = new ArrayList<>();
        try {
            for (JcjcCatrgoryImportExcel cate:cateList) {
                JcjcCategoryReport jcjcCategoryReport = new JcjcCategoryReport();
                Date date = DateUtils.StringToDate(cate.getTaskDate());
                jcjcCategoryReport.setTaskDate(date);
                Map<String,String> lineMap = lineMaps.get(cate.getLineName());

                //查询线路为空，查规则表获取线路名--再查询
                if(null == lineMap){
                    String newName = null;
                    newName = lineRuleMap.get(cate.getLineName());
//                    if(null == newName){
//                        newName = getLineNameByRule(cate.getLineName());
//                        if(null != newName) lineRuleMap.put(cate.getLineName(),newName);
//                    }
                    //查规则表也为空，跳过
                    if(newName == null) {
                        errMsg.put(cate.getLineName(),"线路不存在");
                        continue;
                    }
                    lineMap = lineMaps.get(newName);
                }
                if(null!=lineMap && !lineMap.isEmpty()){
                    jcjcCategoryReport.setLineId(lineMap.get("seclineId"));
                    jcjcCategoryReport.setDeptId(getUnitDeptCode(unitList,lineMap.get("seclineId"),cate.getMileage(),null)!=null?getUnitDeptCode(unitList,lineMap.get("seclineId"),cate.getMileage(),null):lineMap.get("unitDeptCode"));
                }else{
                    errMsg.put(cate.getLineName(),"线路不存在");
                    continue;
                }
                jcjcCategoryReport.setDeptJuId(deptMap.get(cate.getDeptJu()));
                jcjcCategoryReport.setDirectionId(directionMap.get(cate.getDirection()));
                jcjcCategoryReport.setMileage(cate.getMileage());
                jcjcCategoryReport.setSpeed(cate.getSpeed());
                jcjcCategoryReport.setCategoryId(defectCategoryMap.get(cate.getCategoryName()));
                jcjcCategoryReport.setLevelId(defectLevelMap.get(levelMap.get(cate.getLevelName())));
                jcjcCategoryReport.setDefectValue(cate.getDefectValue());
                jcjcCategoryReport.setDeductPoints(cate.getDeductPoints());
                jcjcCategoryReport.setImportId(jcjcRowDataImportLog.getId());
                jcjcCategoryReport.setCreateBy(loginUser.getId());
                jcjcCategoryReport.setCreateDatetime(nowDate);
                jcjcCategoryReport.setDelFlag("N");
                //根据线路，行别，检测日期，日程查询是否存在。存在修改，不存在新增
                JcjcCategoryReport selReport = jcjcCategoryReportServices.queryByParams(lineMap.get("seclineId"),directionMap.get(cate.getDirection()),
                        date,cate.getMileage(),jcjcCategoryReport.getCategoryId(),jcjcCategoryReport.getLevelId());
                if (selReport!=null) {
                    jcjcCategoryReport.setId(selReport.getId());
                }
                if (successCate.containsKey(cate.getLineName())) {
                    Integer sum = successCate.get(cate.getLineName())+ 1;
                    successCate.put(cate.getLineName(),sum);
                }else {
                    successCate.put(cate.getLineName(),1);
                }
                jcjcCategoryReports.add(jcjcCategoryReport);
            }
        }catch (Exception E){  //导入
            //如果导入失败  返回导入失败 并且设置导入为失败
            jcjcRowDataImportLog.setStatus("1");
            jcjcRowDataImportLog.setRemark("读取缺陷报表失败");
            modelMapper.updateById(jcjcRowDataImportLog);
            E.printStackTrace();
//            throw new BizException("读取缺陷报表失败");
        }

        // 解析第二个table 每公里扣分数 JCJC_KM_DEDUCTION
        List<JcjcKmDeduction> jcjcKmDeductions = new ArrayList<>();
        try {
            for (JcjcKmDeductionExcel k:kmList) {
                JcjcKmDeduction jcjcKmDeduction = new JcjcKmDeduction();
                Map<String,String> lineMap = lineMaps.get(k.getLineName());
                //查询线路为空，查规则表获取线路名--再查询
                if(null == lineMap){
                    String newName = null;
                    newName = lineRuleMap.get(k.getLineName());
//                    if(null == newName){
//                        newName = getLineNameByRule(k.getLineName());
//                        if(null != newName) lineRuleMap.put(k.getLineName(),newName);
//                    }
                    //查规则表也为空，跳过
                    if(newName == null) {
                        errMsg.put(k.getLineName(),"线路不存在");
                        continue;
                    }
                    lineMap = lineMaps.get(newName);
                }
                if(null!=lineMap &&  !lineMap.isEmpty()){
                    jcjcKmDeduction.setLineId(lineMap.get("seclineId"));
                    String[] roads = k.getMileage().split("-");
                    jcjcKmDeduction.setDeptId(getUnitDeptCode(unitList,lineMap.get("seclineId"),roads[0].trim(),roads[1].trim())!=null?getUnitDeptCode(unitList,lineMap.get("seclineId"),roads[0].trim(),roads[1].trim()):lineMap.get("unitDeptCode"));
                }else{
                    errMsg.put(k.getLineName(),"线路不存在");
                    continue;
                }
                jcjcKmDeduction.setDirectionId(directionMap.get(k.getDirection()));
                jcjcKmDeduction.setTaskDate(DateUtils.StringToDate(k.getTaskDate()));
                jcjcKmDeduction.setMileage(k.getMileage());// 里程
                jcjcKmDeduction.setSpeed(k.getSpeed()); // 速度
                jcjcKmDeduction.setDeductNum(k.getDeductNum());// 扣分数
                //判断 是否优良  0否1是
                if(k.getGood().equals("否"))jcjcKmDeduction.setIsGood("0");
                else jcjcKmDeduction.setIsGood("1");

                //判断是否合格 0否1是
                if(k.getQualified().equals("否"))jcjcKmDeduction.setIsGood("0");
                else jcjcKmDeduction.setIsQualified("1");

                jcjcKmDeduction.setImportId(jcjcRowDataImportLog.getId());
                jcjcKmDeduction.setCreateBy(loginUser.getId());
                jcjcKmDeduction.setCreateDatetime(nowDate);
                jcjcKmDeduction.setDelFlag("N");
                JcjcKmDeduction selKm = jcjcKmDeductionServices.queryByParams(lineMap.get("seclineId"),directionMap.get(k.getDirection()),
                        DateUtils.StringToDate(k.getTaskDate()),k.getMileage());
                if (selKm!=null) {
                    jcjcKmDeduction.setId(selKm.getId());
                }
                if (successKm.containsKey(k.getLineName())) {
                    Integer sum = successKm.get(k.getLineName())+ 1;
                    successKm.put(k.getLineName(),sum);
                }else {
                    successKm.put(k.getLineName(),1);
                }
                jcjcKmDeductions.add(jcjcKmDeduction);
            }
        }catch (Exception E){
            //如果导入失败  返回导入失败 并且设置导入为失败
            jcjcRowDataImportLog.setStatus("1");
            jcjcRowDataImportLog.setRemark("读取每公里扣分数失败");
            modelMapper.updateById(jcjcRowDataImportLog);
            E.printStackTrace();
//            throw new BizException("读取每公里扣分数失败");
        }

        // 解析第三个table 单元cdi JCJC_UNIT_CID_DATA
        ArrayList<JcjcUnitCidData> jcjcUnitCidDatas = new ArrayList<>();

        try {
            for (JcjcUnitCidDataExcel c:cdiList) {
                JcjcUnitCidData jcjcUnitCidData = new JcjcUnitCidData();
                //查询线路为空，查规则表获取线路名--再查询
                Map<String,String> lineMap = lineMaps.get(c.getLine());
                if(null == lineMap){
                    String newName = null;
                    newName = lineRuleMap.get(c.getLine());
//                    if(null == newName){
//                        newName = getLineNameByRule(c.getLine());
//                        if(null != newName) lineRuleMap.put(c.getLine(),newName);
//                    }
                    //查规则表也为空，跳过
                    if(newName == null){
                        errMsg.put(c.getLine(),"线路不存在");
                        continue;
                    }
                    lineMap = lineMaps.get(newName);
                }
                if(null!=lineMap && !lineMap.isEmpty()){
                    jcjcUnitCidData.setLineId(lineMap.get("seclineId"));
                    String unitDeptCode = deptUnitMap.get(c.getDept());
                    if (StringUtils.isEmpty(unitDeptCode)) {
                        unitDeptCode = getUnitDeptCode(unitList,lineMap.get("seclineId"),c.getBeginMileage(),c.getEndMileage())!=null?getUnitDeptCode(unitList,lineMap.get("seclineId"),c.getBeginMileage(),c.getEndMileage()):lineMap.get("unitDeptCode");
                    }
                    jcjcUnitCidData.setDeptId(unitDeptCode);
                }else{
                    errMsg.put(c.getLine(),"线路不存在");
                    continue;
                }
                jcjcUnitCidData.setCarNo(c.getScrim());// 车号
                jcjcUnitCidData.setPantograph(c.getPantograph());// 受电弓方向
                jcjcUnitCidData.setDirectionId(directionMap.get(c.getDirection()));
                jcjcUnitCidData.setTaskDate(DateUtils.StringToDate(c.getTaskDate()));
                jcjcUnitCidData.setDeptJuId(deptMap.get(c.getDeptJu()));
                jcjcUnitCidData.setBeginMileage(c.getBeginMileage());
                jcjcUnitCidData.setEndMileage(c.getEndMileage());
                jcjcUnitCidData.setUnitLenftg(c.getUnitLenftg());
                jcjcUnitCidData.setAvgSpeed(c.getAvgSpeed());
                jcjcUnitCidData.setArcingRate(c.getArcingRate());
                jcjcUnitCidData.setCdis(c.getCdis());
                jcjcUnitCidData.setCdih(c.getCdih());
                jcjcUnitCidData.setCdif(c.getCdif());
                jcjcUnitCidData.setCdia(c.getCdia());
                jcjcUnitCidData.setCdi(c.getCdi());
                jcjcUnitCidData.setIsEffective(c.getIsEffective());
                jcjcUnitCidData.setIsScore(c.getIsScore());
                jcjcUnitCidData.setImportId(jcjcRowDataImportLog.getId());
                jcjcUnitCidData.setCreateBy(loginUser.getId());
                jcjcUnitCidData.setCreateDatetime(nowDate);
                jcjcUnitCidData.setDelFlag("N");
                JcjcUnitCidData selCid = jcjcUnitCidDataServices.queryByParams(lineMap.get("seclineId"),directionMap.get(c.getDirection()),
                        DateUtils.StringToDate(c.getTaskDate()),c.getBeginMileage(),c.getEndMileage());
                if (selCid!=null) {
                    jcjcUnitCidData.setId(selCid.getId());
                }
                if (successCdi.containsKey(c.getLine())) {
                    Integer sum = successCdi.get(c.getLine())+ 1;
                    successCdi.put(c.getLine(),sum);
                }else {
                    successCdi.put(c.getLine(),1);
                }
                jcjcUnitCidDatas.add(jcjcUnitCidData);
            }

        }catch (Exception E){
            System.out.println(E);
            jcjcRowDataImportLog.setStatus("1");
            jcjcRowDataImportLog.setRemark("读取单元CDI数据失败");
            modelMapper.updateById(jcjcRowDataImportLog);
            E.printStackTrace();
//            throw new BizException("读取单元CDI数据失败");
        }

        //批量保存
        jcjcCategoryReportServices.saveOrUpdateBatch(jcjcCategoryReports);
        jcjcKmDeductionServices.saveOrUpdateBatch(jcjcKmDeductions);
        jcjcUnitCidDataServices.saveOrUpdateBatch(jcjcUnitCidDatas);


        //更新 统计表 JCJC_EVALAUATION_SUMMARY
        String taskDate = cdiList.get(0).getTaskDate();
        vo.setTaskDate(taskDate.substring(0,7));
        //根据时间查线路CDI
        List<Map<String,String>> cdiMaps = modelMapper.findCDIOrderByLineId(vo);

        for (Map<String,String> maps:cdiMaps) {
            vo.setLineId(maps.get("lineId"));
            vo.setDeptId(maps.get("deptId"));
            Map<String, String> sum =null;
            sum= modelMapper.findKMsumIdByLineId(vo);  //根据lineid 检测日期 获取统计表里数据
            if(sum == null){ // 新增
                Map<String,Object> numMap=null;
                numMap=modelMapper.selectNumListByLineId(vo);
                if(!numMap.isEmpty()){
                    BigDecimal scoreLenftg = getBigDecimal(numMap.get("scoreLenftg"));
                    BigDecimal totalLenftg = getBigDecimal(numMap.get("totalLenftg"));
                    BigDecimal uncommentLenftg = getBigDecimal(numMap.get("uncommentLenftg"));
                    BigDecimal cdi = BigDecimal.ZERO;
                    if(!totalLenftg.subtract(uncommentLenftg).equals(BigDecimal.ZERO))
                    {
                        cdi = scoreLenftg.divide(totalLenftg.subtract(uncommentLenftg),4,2);
                    }
                    JcjcEvalauationSummary jcjcEvalauationSummary = new JcjcEvalauationSummary();

                    jcjcEvalauationSummary.setLineId(maps.get("lineId"));
                    jcjcEvalauationSummary.setDeptId(maps.get("deptId"));
                    jcjcEvalauationSummary.setTestDate(DateUtils.StringToDate(taskDate));
                    jcjcEvalauationSummary.setScoreNum(Integer.valueOf(numMap.get("scoreNum").toString()));
                    jcjcEvalauationSummary.setNscoreNum(Integer.valueOf(numMap.get("unscoreNum").toString()));
                    jcjcEvalauationSummary.setCdi(cdi.doubleValue());
                    jcjcEvalauationSummary.setImportId(jcjcRowDataImportLog.getId());
                    jcjcEvalauationSummary.setCreateBy(loginUser.getId());
                    jcjcEvalauationSummary.setCreateDatetime(nowDate);
                    jcjcEvalauationSummary.setDelFlag("N");
                    jcjcEvalauationSummaryServices.save(jcjcEvalauationSummary);
                    Map<String, Object> kmMap = null;
                    kmMap = modelMapper.selectKMNumListByLineId(vo);//公里的
                    if(!kmMap.isEmpty()){
                        BigDecimal excellentNum = getBigDecimal(kmMap.get("excellentNum"));
                        BigDecimal unexcellentNum = getBigDecimal(kmMap.get("unexcellentNum"));
                        BigDecimal excellentRate = BigDecimal.ZERO;
                        if(!excellentNum.add(unexcellentNum).equals(BigDecimal.ZERO)){
                            excellentRate = excellentNum.divide(excellentNum.add(unexcellentNum),2,1);
                        }
                        jcjcEvalauationSummary.setExcellentNum(excellentNum.intValue());
                        jcjcEvalauationSummary.setNexcellectNum(unexcellentNum.intValue());
                        jcjcEvalauationSummary.setExcellectRate(excellentRate.doubleValue());
                        jcjcEvalauationSummaryServices.updateById(jcjcEvalauationSummary);
                    }else{
                        jcjcEvalauationSummary.setExcellentNum(0);
                        jcjcEvalauationSummary.setNexcellectNum(0);
                        jcjcEvalauationSummary.setExcellectRate(0.0);
                        jcjcEvalauationSummaryServices.updateById(jcjcEvalauationSummary);
                    }
                }
            }else{
                Map<String, String> sums = modelMapper.findKMsumIdByLineId(vo);
                BigDecimal cdis = JcjcRowDataImportLogService.getBigDecimal(sums.get("cdi"));
                BigDecimal excellectRates = getBigDecimal(sums.get("excellectRate"));
                //根据lineid  导入日期获取优秀数量  不优秀数量
                Map<String,Object> numMap=modelMapper.selectNumListByLineId(vo);//cdi的
                if(!numMap.isEmpty()) {
                    BigDecimal scoreLenftg = getBigDecimal(numMap.get("scoreLenftg"));
                    BigDecimal totalLenftg = getBigDecimal(numMap.get("totalLenftg"));
                    BigDecimal uncommentLenftg = getBigDecimal(numMap.get("uncommentLenftg"));
                    BigDecimal cdi = BigDecimal.ZERO;
                    if(!totalLenftg.subtract(uncommentLenftg).equals(BigDecimal.ZERO))
                    {
                        cdi = scoreLenftg.divide(totalLenftg.subtract(uncommentLenftg),4,1);
                    }
                    int res = cdi.compareTo(cdis);
                    if(res==1){
                        //大于执行更新
                        JcjcEvalauationSummary jcjcEvalauationSummary = new JcjcEvalauationSummary();
                        jcjcEvalauationSummary.setId((String) sums.get("id"));
                        jcjcEvalauationSummary.setScoreNum(Integer.valueOf(numMap.get("scoreNum").toString()));
                        jcjcEvalauationSummary.setNscoreNum(Integer.valueOf(numMap.get("unscoreNum").toString()));
                        jcjcEvalauationSummary.setCdi(cdi.doubleValue());
                        jcjcEvalauationSummary.setLineId(maps.get("lineId"));
                        jcjcEvalauationSummary.setDeptId(maps.get("deptId"));
                        jcjcEvalauationSummaryServices.updateById(jcjcEvalauationSummary);
                    }
                }
                Map<String, Object> kmMap = modelMapper.selectKMNumListByLineId(vo);//公里的
                if(!kmMap.isEmpty()) {
                    BigDecimal excellentNum = JcjcRowDataImportLogService.getBigDecimal(kmMap.get("excellentNum"));
                    BigDecimal unexcellentNum = JcjcRowDataImportLogService.getBigDecimal(kmMap.get("unexcellentNum"));
                    BigDecimal excellentRate = BigDecimal.ZERO;
                    if(!excellentNum.add(unexcellentNum).equals(BigDecimal.ZERO)){
                        excellentRate = excellentNum.divide(excellentNum.add(unexcellentNum),2,1);
                    }
                    int res = excellentRate.compareTo(excellectRates);
                    if(res==1){
                        //大于执行更新
                        JcjcEvalauationSummary jcjcEvalauationSummary = new JcjcEvalauationSummary();
                        jcjcEvalauationSummary.setId((String) sums.get("id"));
                        jcjcEvalauationSummary.setExcellentNum(excellentNum.intValue());
                        jcjcEvalauationSummary.setNexcellectNum(unexcellentNum.intValue());
                        jcjcEvalauationSummary.setExcellectRate(excellentRate.doubleValue());
                        jcjcEvalauationSummaryServices.updateById(jcjcEvalauationSummary);
                    }
                }

            }
        }
        HashMap<String, Object> map = new HashMap<>();
        int countNum = cdiList.size() + cateList.size() + kmList.size();//总条数
        map.put("countNum",countNum);
        /*map.put("jcjcCategoryReports",jcjcCategoryReports);
        map.put("jcjcKmDeductions",jcjcKmDeductions);
        map.put("jcjcUnitCidData",jcjcUnitCidData);*/

        //【入库成功】：缺陷报表(穗深城际:8条)，每公里扣分数统计(穗深城际:141条、广州东环城际:44条)，
        // 单元CDI数据(广州东环城际:47条、穗深城际:142条)。【入库失败】：广清城际线路不存在，青陕高速不存在。
        StringBuilder remark = new StringBuilder();
        remark.append("【入库成功】:缺陷报表(");
        int i=1;
        for (String key: successCate.keySet()) {
            remark.append(key).append(":").append(successCate.get(key)).append("条");
            if (i<successCate.size()){
                remark.append("、");
            }
            i++;
        }
        remark.append("),");
        remark.append("每公里扣分数统计(");
        i=1;
        for (String key: successKm.keySet()) {
            remark.append(key).append(":").append(successKm.get(key)).append("条");
            if (i<successCate.size()){
                remark.append("、");
            }
            i++;
        }
        remark.append("),");
        remark.append("单元CDI数据(");
        i=1;
        for (String key: successCdi.keySet()) {
            remark.append(key).append(":").append(successCdi.get(key)).append("条");
            if (i<successCate.size()){
                remark.append("、");
            }
            i++;
        }
        remark.append(")。【入库失败】：");
        i=1;
        if (errMsg!=null && errMsg.size()>0) {
            for (String key: errMsg.keySet()) {
                remark.append(key).append(errMsg.get(key));
                if (i<errMsg.size()){
                    remark.append(",");
                }else {
                    remark.append("。");
                }
                i++;
            }
        }else {
            remark.append("无");
        }
        jcjcRowDataImportLog.setStatus("0");
        jcjcRowDataImportLog.setRemark(remark.toString());
        modelMapper.updateById(jcjcRowDataImportLog);
        return map;
    }


    /**
     * 模板下载
     */
    public void download(HttpServletResponse response) {
        String fileName = "数据统计模板.xls";
        String resourcePath = "templates/jcjc_row_data.xls";
        ExpCommonHelper.exportTemplate(response, resourcePath, fileName);
    }

    /**
     * 部门MAP
     */
    private Map<String,String> deptMap(){
        List<SysDept> deptList = sysDeptServices.list();
        Map<String,String> result = deptList.stream().collect(Collectors.toMap(SysDept::getDeptName, SysDept::getDeptId ,
                (entity1, entity2) -> entity1));
        return result;
    }

    /**
     * 部门MAP
     */
    private Map<String,String> deptUnitMap(){
        List<SysDept> deptList = sysDeptServices.list();
        Map<String,String> result = deptList.stream().collect(Collectors.toMap(SysDept::getDeptName, SysDept::getDeptNo ,
                (entity1, entity2) -> entity1));
        return result;
    }

    /**
     *缺陷等级MAP
     */
    private Map<String,String> defectLevelMap(){
        List<JcwProblemDefectLevel> levelList = jcwProblemDefectLevelServices.list();
        Map<String,String> result = levelList.stream().collect(Collectors.toMap(JcwProblemDefectLevel::getLevelName, JcwProblemDefectLevel::getId , (entity1, entity2) -> entity1));
        return result;
    }

    /**
     * 缺陷类型MAP
     */
    private Map<String,String> defectCategoryMap(){
        List<JcwProblemDefectCategory> categoryList = jcwProblemDefectCategoryServices.list();
        Map<String,String> result = categoryList.stream().collect(Collectors.toMap(JcwProblemDefectCategory::getCategoryName, JcwProblemDefectCategory::getId, (entity1, entity2) -> entity1));
        return result;
    }

    /**
     * 行别MAP
     */
    private Map<String,String> directionMap(){
        List<JcDirection> directionList = jcDirectionServices.list();
        Map<String,String> result = directionList.stream().collect(Collectors.toMap(JcDirection::getDirectionName, JcDirection::getDirectionId, (entity1, entity2) -> entity1));
        return result;
    }

    private static BigDecimal getBigDecimal(Object value ) {
        BigDecimal ret = null;
        if( value != null ) {
            if( value instanceof BigDecimal ) {
                ret = (BigDecimal) value;
            } else if( value instanceof String ) {
                ret = new BigDecimal( (String) value );
            } else if( value instanceof BigInteger) {
                ret = new BigDecimal( (BigInteger) value );
            } else if( value instanceof Number ) {
                ret = new BigDecimal( ((Number)value).doubleValue() );
            } else {
                throw new ClassCastException("Not possible to coerce ["+value+"] from class "+value.getClass()+" into a BigDecimal.");
            }
        }
        return ret;
    }

//    //根据规则查询生产线路名称
//    public String getLineNameByRule(String sourceName) {
//        String ruleType = KfkErrorTypeEnum.LINE.getType();
//        JcCategoryReportRule rule = jcCategoryReportRuleService.getByRuleTypeAndSourceData(ruleType,sourceName);
//        if (rule!=null) {
//            return rule.getOptData();
//        }
//        return null;
//    }

    //根据线路和公里标获取部门code
    public String getUnitDeptCode(List<Map<String,Object>> unitList, String seclineId, String beginMileage, String endMileage) {
        String unitDeptCode = null;
        for (Map<String, Object> unit : unitList) {
            if (seclineId.equals(unit.get("seclineId"))) {
                BigDecimal beginRoad = new BigDecimal(unit.get("beginRoad").toString());
                BigDecimal endRoad = new BigDecimal(unit.get("endRoad").toString());
                if (StringUtils.isNotBlank(endMileage)) {
                    if (beginRoad.doubleValue()<=Double.parseDouble(beginMileage)
                            && endRoad.doubleValue()>=Double.parseDouble(endMileage)) {
                        unitDeptCode = unit.get("unitDeptCode").toString();
                        break;
                    }
                }else {

                    if (beginRoad.doubleValue()<=Double.parseDouble(beginMileage)
                            && endRoad.doubleValue()>=Double.parseDouble(beginMileage)) {
                        unitDeptCode = unit.get("unitDeptCode").toString();
                        break;
                    }
                }
            }
        }
        return unitDeptCode;
    }
    /**
     * 查询线路规则
     */
//    public String checkLine(String lineName) {
//        String newName = null;
//        String errorType = KfkErrorTypeEnum.LINE.getType();
//        List<KfkConsumerRule> ruleList = kfkConsumerRuleService.findByErrorType(errorType, "itps_defect_gz");
//        for (KfkConsumerRule o : ruleList) {
//            //防止没有该字段报错
//            if (o.getType() == null) {
//                continue;
//            }
//            if (o.getType() == 0) {
//                //编码预处理,按编码或名称
//                String key = o.getErrorType() + o.getErrorCode();
//                //按异常编码进行匹配校正
//                boolean nameFlag = StringUtils.isNotBlank(lineName) && key.equals(errorType + lineName);
//                if (nameFlag) {
//                    newName = JSON.parseObject(JSON.toJSONString(o.getData()), KfkRuleLine.class).getLineName();
//                    break;
//                }
//            } else if (o.getType() == 1 && StringUtils.isNotBlank(lineName)) {
//                //别名预处理，按名称
//                for (String rule : o.getRuleList()) {
//                    if (lineName.equals(rule)) {
//                        newName = JSON.parseObject(JSON.toJSONString(o.getData()), LineAttr.class).getLineCode();
//                        break;
//                    }
//                }
//            } else if (o.getType() == 2 && StringUtils.isNotBlank(lineName)) {
//                //替换预处理,按名称
//                for (String rule : o.getRuleList()) {
//                    if (lineName.endsWith(rule)) {
//                        newName = lineName.substring(0, lineName.lastIndexOf(rule)) + ObjectUtil.covToString(o.getData()).replaceAll("\\s*", "");
//                        break;
//                    }
//                }
//            }
//        }
//
//        return newName;
//    }
}
